package com.FH.permission.sys_role_menu;

import com.FH.util.AccessDB;
import com.FH.util.ResultDTO;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import javax.ejb.Stateless;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Stateless
public class SysRoleMenuDAOImpl extends AccessDB implements SysRoleMenuDAO {

    @Override
    public ResultDTO addSysRoleMenu(SysRoleMenuPullDTO sysRoleMenuPullDTO) {
        ResultDTO resultDTO = new ResultDTO();

        int resultls = 0;

        if(sysRoleMenuPullDTO.getSys_menu_id().length > 0){

            String deleteSql = "delete from sys_role_menu where sys_role_id = " + sysRoleMenuPullDTO.getSys_role_id();

            addReportingTo(deleteSql);

            for(int i=0;i<sysRoleMenuPullDTO.getSys_menu_id().length;i++){
                String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");

                String sql = "insert into sys_role_menu (sys_role_menu_id,sys_role_id,sys_menu_id) values ('" + uuid + "',"
                        + sysRoleMenuPullDTO.getSys_role_id() + ",'" + sysRoleMenuPullDTO.getSys_menu_id()[i] + "')";
                resultls = this.addReportingTo(sql);
            }

        }

        if (resultls != 0) {
            resultDTO.setStatus("90000");//
            resultDTO.setDescritpion("菜单分配成功");
        } else {
            resultDTO.setStatus("90001");//
            resultDTO.setDescritpion("菜单分配失败");
        }

        return resultDTO;
    }

    @Override
    public ResultDTO getMenuBySysRole(String search) {

        ResultDTO resultDTO = new ResultDTO();

        List<String[]> result = new ArrayList<String[]>();

        try {
            JSONObject jsonObject = new JSONObject(search);

            String sql = "SELECT DISTINCT sys_menu_id FROM sys_role_menu WHERE 1=1 ";

            if(jsonObject.has("sys_role_id")){

                sql += " and sys_role_id =" + jsonObject.get("sys_role_id");
            }

            result = this.getReportingTo(sql);

        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (result.size() > 0) {
            resultDTO.setStatus("90000");//
            resultDTO.setDescritpion("菜单分配成功");
            resultDTO.setValues(result);
        } else {
            resultDTO.setStatus("90001");//
            resultDTO.setDescritpion("菜单分配失败");
        }

        return resultDTO;

    }
}
